package com.zhouheng.springbootmultithreading.tuling.lock;

import lombok.extern.log4j.Log4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhouheng
 */
@Log4j
public class ReadWriteLockTest2 {

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void red() {
        log.info("准备获取读锁...");
        lock.readLock().lock();
        try {
            log.info("获取读锁，读取数据");
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
            log.info("释放读锁");
        }
    }

    public void write() {
        log.info("准备获取写锁...");
        lock.writeLock().lock();
        try {
            log.info("获取写锁，写入数据");
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
            log.info("释放写锁");
        }
    }


    public static void main(String[] args) throws InterruptedException {
        ReadWriteLockTest2 test = new ReadWriteLockTest2();

        // 测试读读，读写，写读，写写的场景
        // 测试结果只有读读不会互斥，其他都会互斥
        new Thread(() -> test.write(), "thread1").start();
        Thread.sleep(10);
        new Thread(() -> test.write(), "thread2").start();
    }


}